package com.itguigu.glimail.oauth.controller;

import com.alibaba.fastjson.TypeReference;
import com.itguigu.common.constant.AuthServerContant;
import com.itguigu.common.exception.BizCodeEnume;
import com.itguigu.common.utils.R;
import com.itguigu.glimail.oauth.feign.MemberFeignService;
import com.itguigu.glimail.oauth.feign.ThirdPartyFeignService;
import com.itguigu.glimail.oauth.vo.MemberRespVo;
import com.itguigu.glimail.oauth.vo.UserLoginVo;
import com.itguigu.glimail.oauth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    //    @GetMapping("reg.html")
//    public String register() {
//        return "reg";
//
//    }
    @GetMapping("login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerContant.LOGIN_USER);

        if (attribute == null) {

            return "login";
        } else {
            return "redirect:http://glimail.com";
        }

    }
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * todo接口防刷
     * 验证码再次校验  redis
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //todo 接口防刷.
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerContant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {

            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 600000) {

                //60s内不发送
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());

            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        String redisPhoneCode = code + "_" + System.currentTimeMillis();
        //防止防刷
        stringRedisTemplate.opsForValue().set(AuthServerContant.SMS_CODE_CACHE_PREFIX + phone, redisPhoneCode, 60, TimeUnit.MINUTES);

//        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * @param userVo
     * @param result
     * @param redirectAttributes 模拟重定向携带数据
     *                           todo 重定向携带数据,利用session原理 将数据放到session中
     *                           todo 只要调到下一个页面取出这个数据后,session中的数据会清楚
     *                           TODO 分布式下session的问题
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo userVo, BindingResult result,
                         /**Model model*/RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            //校验出错  转发注册页面
//          Map<String, String> errorMap = new HashMap<>();
//           result.getFieldErrors().stream().map(fieldError -> {
//                String field = fieldError.getField();
//                String defaultMessage = fieldError.getDefaultMessage();
//                errorMap.put(field, defaultMessage);
//                return errorMap;
//            }).collect(to);
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            //Request method 'POST' not supported
            //用户注册 ->/regist[post] --->转发reg.html(路径映射默认都是get形式访问)
            // 解决  直接return reg
//            return "forward:/reg.html";
//            return "reg";//导致重复提交  解决 重定向
            //校验出错,转发注册页
            return "redirect:http://auth.glimail.com/reg.html"; //但是会丢失数据  解决 RedirectAttributes替换Model
        }
        //真正的注册  调用远程服务
        //校验验证码
        String code = userVo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerContant.SMS_CODE_CACHE_PREFIX + userVo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                //验证码通过  调用远程服务注册
                //校验成功 删除验证码  令牌机制
                stringRedisTemplate.delete(AuthServerContant.SMS_CODE_CACHE_PREFIX + userVo.getPhone());
                //验证码通过  调用远程服务注册
                R regist = memberFeignService.regist(userVo);
                if (regist.getCode() == 0) {
                    //成功

                    return "redirect:http://auth.glimail.com/login.html";
                } else {
                    //失败 转发注册页
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", regist.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.glimail.com/reg.html";
                }

            } else {
                HashMap<String, String> map = new HashMap<>();
                map.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", map);
                //校验出错,转发注册页
                return "redirect:http://auth.glimail.com/reg.html"; //但是会丢失数据  解决 RedirectAttributes替换Model
            }
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", map);
            //校验出错,转发注册页
            return "redirect:http://auth.glimail.com/reg.html"; //但是会丢失数据  解决 RedirectAttributes替换Model
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {
//远程登录
        R login = memberFeignService.login(userLoginVo);
        if (login.getCode() == 0) {
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerContant.LOGIN_USER,data);
            return "redirect:http://glimail.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.glimail.com/login.html";
        }
    }

}
